<template>
  <div class="user-audit-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>用户审核管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button type="warning" @click="forceRefresh" style="margin-left: 10px;">强制刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" :key="renderKey">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.pending }}</div>
              <div class="stats-label">待审核</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.approved }}</div>
              <div class="stats-label">已通过</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.rejected }}</div>
              <div class="stats-label">已拒绝</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.total }}</div>
              <div class="stats-label">总计</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已通过" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="收款商户名/审核人" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">审核列表</div>
        <div class="table-actions">
          <el-button type="success" @click="handleBatchApprove" :disabled="!selectedRows.length">
            批量通过
          </el-button>
          <el-button type="danger" @click="handleBatchReject" :disabled="!selectedRows.length">
            批量拒绝
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="用户信息" width="200">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar 
                :src="scope.row.userAvatar" 
                size="small"
                :icon="!scope.row.userAvatar ? 'el-icon-user' : ''"
              ></el-avatar>
              <span class="user-name">{{ scope.row.userNickname || scope.row.user_nickname || '未知用户' }}</span>
              <div style="font-size: 12px; color: #999;">ID: {{ scope.row.userId }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="收款商户名" width="150">
          <template slot-scope="scope">
            {{ scope.row.realName || scope.row.real_name || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="收款码" width="120">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.bankQrcodeUrl || scope.row.bank_qrcode_url"
              :src="scope.row.bankQrcodeUrl || scope.row.bank_qrcode_url"
              :preview-src-list="[scope.row.bankQrcodeUrl || scope.row.bank_qrcode_url]"
              style="width: 60px; height: 60px"
              fit="cover"
            ></el-image>
            <span v-else style="color: #999;">无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusText || getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核备注" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.auditRemark || scope.row.audit_remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核人" width="100">
          <template slot-scope="scope">
            {{ scope.row.auditorName || scope.row.auditor_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="提交时间" width="160">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime || scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" width="160">
          <template slot-scope="scope">
            {{ (scope.row.auditTime || scope.row.audit_time) ? formatTime(scope.row.auditTime || scope.row.audit_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="mini"
              type="success"
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="mini"
              type="danger"
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="computedPagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="computedPagination.count"
          layout="total, sizes, prev, pager, next, jumper"
          :total="computedPagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog title="审核操作" :visible.sync="auditDialogVisible" width="500px">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.action">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAudit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="审核详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentDetail.userId }}</el-descriptions-item>
          <el-descriptions-item label="用户昵称">
            {{ currentDetail.userNickname || currentDetail.user_nickname || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="收款商户名">
            {{ currentDetail.realName || currentDetail.real_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ currentDetail.statusText || currentDetail.status_text || getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">{{ currentDetail.auditorName || currentDetail.auditor_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ (currentDetail.auditTime || currentDetail.audit_time) ? formatTime(currentDetail.auditTime || currentDetail.audit_time) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatTime(currentDetail.createTime || currentDetail.create_time) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(currentDetail.updateTime || currentDetail.update_time) }}</el-descriptions-item>
          <el-descriptions-item label="审核备注" :span="2">
            {{ currentDetail.auditRemark || currentDetail.audit_remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="qrcode-section">
          <h4>收款码</h4>
          <el-image
            v-if="currentDetail.bankQrcodeUrl || currentDetail.bank_qrcode_url"
            :src="currentDetail.bankQrcodeUrl || currentDetail.bank_qrcode_url"
            :preview-src-list="[currentDetail.bankQrcodeUrl || currentDetail.bank_qrcode_url]"
            style="width: 200px; height: 200px"
            fit="cover"
          ></el-image>
          <div v-else style="color: #999; text-align: center; padding: 40px;">
            暂无收款码图片
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAuditList, getAuditDetail, approveAudit, rejectAudit, getAuditStats, batchApproveAudits, batchRejectAudits } from '@/api/user-audit'

export default {
  name: 'UserAuditList',
  data() {
    return {
      loading: false,
      tableData: [],
      selectedRows: [],
      stats: {
        pending: 0,
        approved: 0,
        rejected: 0,
        total: 0
      },
      searchForm: {
        status: '',
        keyword: ''
      },
      pagination: {
        page: 1,
        count: 10,
        total: 0
      },
      auditDialogVisible: false,
      detailDialogVisible: false,
      currentDetail: null,
      auditForm: {
        action: 'approve',
        remark: ''
      },
      currentAuditId: null,
      // 防抖定时器
      refreshTimer: null,
      // 强制重新渲染的key
      renderKey: 0
    }
  },
  mounted() {
    this.loadData()
    this.loadStats()
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('visibilitychange', this.handleVisibilityChange)
    // 清理定时器
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer)
    }
  },
  activated() {
    // 当页面被激活时（从其他页面返回），重新加载数据
    this.loadData()
    this.loadStats()
  },
  // 监听路由变化
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 路由进入时重新加载数据
      console.log('路由进入，重新加载数据')
      vm.loadData()
      vm.loadStats()
    })
  },
  beforeRouteUpdate(to, from, next) {
    // 路由更新时重新加载数据
    console.log('路由更新，重新加载数据')
    this.loadData()
    this.loadStats()
    next()
  },
  computed: {
    // 计算属性确保统计数据响应式更新
    computedStats() {
      return {
        pending: this.stats.pending || 0,
        approved: this.stats.approved || 0,
        rejected: this.stats.rejected || 0,
        total: this.stats.total || 0
      }
    },
    // 计算属性确保分页数据响应式更新
    computedPagination() {
      return {
        page: this.pagination.page,
        count: this.pagination.count,
        total: this.pagination.total || 0
      }
    }
  },
  watch: {
    // 监听路由变化
    '$route'(to, from) {
      // 如果路由发生变化，防抖重新加载数据
      console.log('路由监听器触发:', to.path, '->', from.path)
      if (to.path !== from.path) {
        console.log('路径变化，触发防抖刷新')
        this.debounceRefresh()
      }
    }
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page - 1,
          count: this.pagination.count,
          status: this.searchForm.status,
          keyword: this.searchForm.keyword
        }
        const response = await getAuditList(params)
        console.log('列表API响应:', response)
        this.tableData = response.items || []
        this.pagination.total = response.total || 0
        console.log('设置后的tableData长度:', this.tableData.length)
        console.log('设置后的pagination.total:', this.pagination.total)
      } catch (error) {
        this.$message.error('加载数据失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // 加载统计
    async loadStats() {
      try {
        console.log('开始加载统计数据...')
        const response = await getAuditStats()
        console.log('统计API响应:', response)
        
        // 直接赋值，因为stats已经在data中初始化了
        if (response) {
          this.stats.pending = response.pending || 0
          this.stats.approved = response.approved || 0
          this.stats.rejected = response.rejected || 0
          this.stats.total = response.total || 0
        } else {
          this.stats.pending = 0
          this.stats.approved = 0
          this.stats.rejected = 0
          this.stats.total = 0
        }
        
        console.log('设置后的stats:', this.stats)
        // 增加renderKey强制重新渲染
        this.renderKey++
        // 强制更新视图
        this.$nextTick(() => {
          this.$forceUpdate()
          console.log('视图强制更新完成')
        })
      } catch (error) {
        console.error('加载统计失败', error)
        this.stats.pending = 0
        this.stats.approved = 0
        this.stats.rejected = 0
        this.stats.total = 0
      }
    },

    // 刷新数据
    async refreshData() {
      // 清空选中的行
      this.selectedRows = []
      // 重新加载数据和统计
      await this.loadData()
      await this.loadStats()
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        status: '',
        keyword: ''
      }
      this.handleSearch()
    },

    // 分页处理
    handleSizeChange(val) {
      this.pagination.count = val
      this.loadData()
    },

    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadData()
    },

    // 选择处理
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 查看详情
    async handleView(row) {
      try {
        const response = await getAuditDetail(row.id)
        this.currentDetail = response
        this.detailDialogVisible = true
      } catch (error) {
        this.$message.error('获取详情失败')
      }
    },

    // 审核通过
    handleApprove(row) {
      this.currentAuditId = row.id
      this.auditForm.action = 'approve'
      this.auditForm.remark = ''
      this.auditDialogVisible = true
    },

    // 审核拒绝
    handleReject(row) {
      this.currentAuditId = row.id
      this.auditForm.action = 'reject'
      this.auditForm.remark = ''
      this.auditDialogVisible = true
    },

    // 确认审核
    async confirmAudit() {
      if (this.auditForm.action === 'reject' && !this.auditForm.remark.trim()) {
        this.$message.warning('拒绝时必须填写备注')
        return
      }

      try {
        if (this.auditForm.action === 'approve') {
          await approveAudit(this.currentAuditId, this.auditForm.remark)
          this.$message.success('审核通过成功')
        } else {
          await rejectAudit(this.currentAuditId, this.auditForm.remark)
          this.$message.success('审核拒绝成功')
        }
        this.auditDialogVisible = false
        // 清空选中的行
        this.selectedRows = []
        // 重新加载数据和统计
        await this.loadData()
        await this.loadStats()
      } catch (error) {
        this.$message.error('审核操作失败')
      }
    },

    // 批量通过
    async handleBatchApprove() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要审核的记录')
        return
      }

      try {
        await this.$confirm('确认批量通过选中的记录？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const ids = this.selectedRows.map(row => row.id)
        await batchApproveAudits(ids)
        this.$message.success('批量通过成功')
        // 清空选中的行
        this.selectedRows = []
        // 重新加载数据和统计
        await this.loadData()
        await this.loadStats()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量操作失败')
        }
      }
    },

    // 批量拒绝
    async handleBatchReject() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要审核的记录')
        return
      }

      try {
        const { value: remark } = await this.$prompt('请输入拒绝原因', '批量拒绝', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea',
          inputPlaceholder: '请输入拒绝原因'
        })

        if (!remark.trim()) {
          this.$message.warning('拒绝原因不能为空')
          return
        }

        const ids = this.selectedRows.map(row => row.id)
        await batchRejectAudits(ids, remark)
        this.$message.success('批量拒绝成功')
        // 清空选中的行
        this.selectedRows = []
        // 重新加载数据和统计
        await this.loadData()
        await this.loadStats()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量操作失败')
        }
      }
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'pending':
          return 'warning'
        case 'approved':
          return 'success'
        case 'rejected':
          return 'danger'
        default:
          return 'info'
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待审核'
        case 'approved':
          return '已通过'
        case 'rejected':
          return '已拒绝'
        default:
          return '未知状态'
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      try {
        return new Date(time).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      } catch (error) {
        console.error('时间格式化错误:', error, time)
        return time
      }
    },

    // 处理页面可见性变化
    handleVisibilityChange() {
      if (!document.hidden) {
        // 页面变为可见时，防抖重新加载数据
        this.debounceRefresh()
      }
    },

    // 防抖刷新
    debounceRefresh() {
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer)
      }
      this.refreshTimer = setTimeout(() => {
        console.log('防抖刷新执行')
        this.loadData()
        this.loadStats()
      }, 300)
    },

    // 强制刷新（用于测试）
    forceRefresh() {
      console.log('强制刷新执行')
      this.loadData()
      this.loadStats()
    }
  }
}
</script>

<style scoped>
.user-audit-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stats-label {
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 14px;
  color: #303133;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  padding: 20px 0;
}

.qrcode-section {
  margin-top: 20px;
  text-align: center;
}

.qrcode-section h4 {
  margin-bottom: 15px;
  color: #303133;
}
</style> 